package com.fencing_squad.homo.page;

import com.alibaba.fastjson.JSONObject;
import com.fencing_squad.homo.ResourceTable;
import com.fencing_squad.homo.util.AnimationConfig;
import com.fencing_squad.homo.util.CustomComponent;
import com.fencing_squad.homo.util.Data;
import com.fencing_squad.homo.util.Network;
import com.fencing_squad.homo.list.Offer;
import com.fencing_squad.homo.util.function.FunctionString;
import com.fencing_squad.homo.util.function.FunctionVoid;
import ohos.agp.animation.AnimatorGroup;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Picker;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class Receive {
    private Component receive = null;

    private List<Component> imageLayouts;

    private List<Image> images;

    private int[] lefts = new int[9];

    private int[] tops = new int[9];

    private List<AnimatorValue> propertiesShow;

    private List<AnimatorValue> propertiesHide;

    private Context context;

    private Component refresh;

    private int top = 0;

    private int left = 0;

    private AnimatorGroup animatorGroupHide;

    private AnimatorGroup animatorGroupShow;

    private List<Offer> offers;

    private CommonDialog dialog;

    private FunctionVoid redirectToLogin;

    private CommonDialog window;

    private final String[] receiveType = new String[] {"全部", "购物", "取件", "送件", "打印", "签字", "组队"};

    private final String[] receiveLevel = new String[] {"全部", "海外", "室外", "公共场所", "教学楼", "办公楼", "寝室楼"};

    private String type = "全部";

    private String level = "全部";

    private Offer currentOffer = null;

    private FunctionString checkOfferDetail;

    public Component get(Context context, FunctionVoid redirectToLogin, FunctionString checkOfferDetail) {
        this.checkOfferDetail = checkOfferDetail;
        this.context = context;
        this.redirectToLogin = redirectToLogin;
        if (receive == null) {
            receive = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_receive, null, false);
        }
        if (imageLayouts == null) {
            imageLayouts = new ArrayList<>();
        }
        if (images == null) {
            images = new ArrayList<>();
        }
        if (propertiesShow == null) {
            propertiesShow = new ArrayList<>();
        }
        if (propertiesHide == null) {
            propertiesHide = new ArrayList<>();
        }
        if (offers == null) {
            offers = new ArrayList<>();
        }
        refresh = receive.findComponentById(ResourceTable.Id_refresh);
        initImage();

        refresh();
        refresh.setClickedListener(component -> {
            refresh();
        });

        Picker receiveType = (Picker) receive.findComponentById(ResourceTable.Id_receiveType);
        receiveType.setTouchEventListener(((component, touchEvent) -> true));
        receiveType.setDisplayedData(this.receiveType);
        receiveType.setValueChangedListener((picker,oldVal,newVal)->{
            type = this.receiveType[newVal];
        });

        Picker receiveLevel = (Picker) receive.findComponentById(ResourceTable.Id_receiveLevel);
        receiveLevel.setTouchEventListener(((component, touchEvent) -> true));
        receiveLevel.setDisplayedData(this.receiveLevel);
        receiveLevel.setValueChangedListener((picker,oldVal,newVal)->{
            level = this.receiveLevel[newVal];
        });

        return receive;
    }

    public void initImage() {
        if (imageLayouts != null && receive != null) {
            imageLayouts.add(receive.findComponentById(ResourceTable.Id_layout1));
            imageLayouts.add(receive.findComponentById(ResourceTable.Id_layout2));
            imageLayouts.add(receive.findComponentById(ResourceTable.Id_layout3));
            imageLayouts.add(receive.findComponentById(ResourceTable.Id_layout4));
            imageLayouts.add(receive.findComponentById(ResourceTable.Id_layout5));
            imageLayouts.add(receive.findComponentById(ResourceTable.Id_layout6));
            imageLayouts.add(receive.findComponentById(ResourceTable.Id_layout7));
            imageLayouts.add(receive.findComponentById(ResourceTable.Id_layout8));
            imageLayouts.add(receive.findComponentById(ResourceTable.Id_layout9));
        }
        if (images != null && receive != null) {
            images.add((Image) receive.findComponentById(ResourceTable.Id_img1));
            images.add((Image) receive.findComponentById(ResourceTable.Id_img2));
            images.add((Image) receive.findComponentById(ResourceTable.Id_img3));
            images.add((Image) receive.findComponentById(ResourceTable.Id_img4));
            images.add((Image) receive.findComponentById(ResourceTable.Id_img5));
            images.add((Image) receive.findComponentById(ResourceTable.Id_img6));
            images.add((Image) receive.findComponentById(ResourceTable.Id_img7));
            images.add((Image) receive.findComponentById(ResourceTable.Id_img8));
            images.add((Image) receive.findComponentById(ResourceTable.Id_img9));
        }
        for (int i = 0; i< Objects.requireNonNull(images).size(); i++) {
            Image image = images.get(i);
            int finalI = i;
            image.setClickedListener(component -> {
                this.checkOffer(finalI);
            });
        }
        setCoordinate();
    }

    public void setCoordinate() {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if (imageLayouts == null) {
                    return;
                }
                for(int i = 0; i< imageLayouts.size(); i++) {
                    Component image = imageLayouts.get(i);
                    lefts[i] = image.getLeft();
                    tops[i] = image.getTop();
                    System.out.println("img");
                    System.out.println(lefts[i]);
                    System.out.println(tops[i]);
                }
                top = refresh.getTop();
                left = refresh.getLeft();

                if (lefts[8] != 0 && tops[8] != 0 && top != 0 && left != 0) {
                    createAnim();
                    timer.cancel();
                }
            }
        };
        timer.schedule(timerTask, 300, 300);
    }

    public void createAnim() {
        for(int i = 0; i< imageLayouts.size(); i++) {
            Component image = imageLayouts.get(i);
            propertiesShow.add(AnimationConfig.getCardAnim(image, left, top, lefts[i], tops[i]));
            propertiesHide.add(AnimationConfig.getCardAnim(image, lefts[i], tops[i], left, top));
        }
        animatorGroupHide = new AnimatorGroup();
        animatorGroupHide.runParallel(propertiesHide.get(0), propertiesHide.get(1), propertiesHide.get(2), propertiesHide.get(3), propertiesHide.get(4), propertiesHide.get(5), propertiesHide.get(6), propertiesHide.get(7), propertiesHide.get(8));
        animatorGroupShow = new AnimatorGroup();
        animatorGroupShow.runParallel(propertiesShow.get(0), propertiesShow.get(1), propertiesShow.get(2), propertiesShow.get(3), propertiesShow.get(4), propertiesShow.get(5), propertiesShow.get(6), propertiesShow.get(7), propertiesShow.get(8));
        AnimationConfig.setAnimationListener(animatorGroupHide, () -> {
            animatorGroupShow.start();
        }, null);
    }

    private void checkOffer(int index) {
        images.get(index).setPixelMap(ResourceTable.Media_card_front);
        if (offers != null && offers.size() > index) {
            this.currentOffer = offers.get(index);
            window = CustomComponent.getOfferDetail(context, this::submit, currentOffer);
            window.show();
        }
    }

    public void submit(String rewardId) {
        if (!Data.Account.isLogin) {
            if (window != null) {
                window.hide();
            }
            redirectToLogin.func();
        }
        else {
            JSONObject object = new JSONObject();
            object.put("reward_id", rewardId);
            Network.postJson("/reward/take", object.toJSONString(), this::take, this::reject);
        }
    }

    private void take(JSONObject object) {
        if (window != null) {
            window.hide();
        }
        checkOfferDetail.func(currentOffer.getRewardId());
    }

    public void refresh() {
        if (animatorGroupShow != null && animatorGroupHide != null) {
            animatorGroupHide.start();
        }
        for (Image image : images) {
            image.setPixelMap(ResourceTable.Media_card_back);
        }
        Map<String, String> params = new ConcurrentHashMap<>();
        if (!level.equals("全部")) {
            params.put("level", level);
        }
        if (!type.equals("全部")) {
            params.put("type", type);
        }
        Network.get("/reward", params, this::refreshResolve, this::reject);
    }

    public void refreshResolve(JSONObject object) {
        if (offers != null) {
            offers.clear();
            offers.addAll(Offer.getFromJSONArray(object.getJSONArray("data")));
        }
    }

    private void reject(int code, String message) {
        if(code == 404) {
            dialog = CustomComponent.getDialog(context, message, () -> {
                if(dialog != null) {
                    dialog.hide();
                }
            }, () -> {
                if(dialog != null) {
                    dialog.hide();
                }
            });
            dialog.show();
        }
        else {
            System.out.println(message);
        }
    }
}
